from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

from .. models import Goods,Types

from . TypesViews import GetTypesAll
from . UserViews import uploads


from django.contrib.auth.decorators import permission_required


# 商品列表
@permission_required('myadmin.show_goods',raise_exception=True)

def index(request):


    # 获取所有的商品
    obs = Goods.objects.filter()


    # 数据分页
    # 获取当前页的页数
    pageindex = request.GET.get('p',1)
    # 导入分页类
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(obs, 10)

    # 获取当前页的 数据
    goodslist = p.page(pageindex)

    # 分配数据
    context = {'goodslist':goodslist}

    # 加载模板
    return render(request,'admin/goods/index.html',context)

# 商品添加页面
@permission_required('myadmin.insert_goods',raise_exception=True)

def add(request):

    context = {'typelist':GetTypesAll(request)}
    
    return render(request,'admin/goods/add.html',context)

# 执行商品添加
@permission_required('myadmin.insert_goods',raise_exception=True)

def insert(request):

    # 获取数据
    data = request.POST.dict()
    del data['csrfmiddlewaretoken']

    # 判断是否有文件上传
    myfile = request.FILES.get('pic',None)
    if myfile:
        # 上传图片 uploads
        data['pic'] = uploads(myfile)
    else:
        return HttpResponse('<script>alert("必须上传图片");history.back(-1);</script>')

    # 创建时,外键的值 要求是个对象
    data['tid'] = Types.objects.get(id=data['tid'])
    # 执行添加
    res = Goods.objects.create(**data)
    if res:
        return HttpResponse('<script>alert("商品添加成功");location.href="/myadmin/goods/index/"</script>')
    else:
        return HttpResponse('<script>alert("商品添加失败");history.back(-1)"</script>')


# 执行商品删除
@permission_required('myadmin.del_goods',raise_exception=True)
def delete(request,gid):
    info = Goods.objects.get(id=gid)

    if info :
        info.delete()
        return HttpResponse('<script>alert("删除成功");location.href="/myadmin/goods/index/"</script>')
    else :
        return HttpResponse('<script>alert("删除失败，该商品不存在");history.back(-1);</script>')
    



# 商品编辑
@permission_required('myadmin.edit_goods',raise_exception=True)

def edit(request,gid):
    # 获取商品信息
    ob = Goods.objects.get(id=gid)
    
    # 分配数据
    context = {'ginfo':ob}

    # 加载模板
    return render(request,'admin/goods/edit.html',context)


# 执行商品的更新
@permission_required('myadmin.edit_goods',raise_exception=True)

def update(request):
    return HttpResponse('update')





